package com.zhou.filter;

import cn.hutool.json.JSONUtil;
import com.zhou.common.UserContext;
import com.zhou.test.entity.SystemUser;
import com.zhou.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: zhoujinchuan
 * @Description: TODO (用一句话描述一下)
 * @Date: 2022/5/8 11:15
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            return false;
        }
        //解析token
        SystemUser user;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            user = JSONUtil.toBean(claims.getSubject(),SystemUser.class);
        } catch (Exception e) {
            throw new RuntimeException("请登录");
        }
        UserContext.setUser(user);
        //放行
        return true;
    }

}
